package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import trip.Company;
import trip.HibernateUtil;
import trip.Route;

public class CompanyDAOImpl extends GenericDaoImpl<Company>  implements CompanyDAO {
	
	public CompanyDAOImpl(Class<Company> type) {
		super(type);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Company> getByName(String name) {
		Session session = null;
		List<Company> result = new ArrayList<Company>();
		if (name == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select c from Company c where c.name like :template");
			query.setString("template", "%" + name + "%");
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Company> getByRoute(Route route) {
		Session session = null;
		List<Company> result = new ArrayList<Company>();
		if (route == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select distinct t.company "
					+ "from Trip t "
					+ "where t.route = :id");
			query.setLong("id", route.getId());
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}
}
